<!DOCTYPE html>













<html class="theme-next gemini" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.4.2',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  





  <meta name="description" content="前言最短路，即在一个加权图G中某两点相距的最短路程的长度（有时要求记录路径）。 单源与多源最短路计算最短路，通常不会只求某两点的最短路，而会将许多点对间的最短路一起算出来。这具体表现在：">
<meta name="keywords" content="模板,专题,最短路,Dijkstra">
<meta property="og:type" content="article">
<meta property="og:title" content="最短路算法·ShortestPath">
<meta property="og:url" content="https://sshwy.gitee.io/2018/10/03/726/index.html">
<meta property="og:site_name" content="Sailor&#39;s Blog">
<meta property="og:description" content="前言最短路，即在一个加权图G中某两点相距的最短路程的长度（有时要求记录路径）。 单源与多源最短路计算最短路，通常不会只求某两点的最短路，而会将许多点对间的最短路一起算出来。这具体表现在：">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://www.z4a.net/images/2018/08/04/dijkstra_glf.gif">
<meta property="og:updated_time" content="2018-11-17T15:41:31.898Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="最短路算法·ShortestPath">
<meta name="twitter:description" content="前言最短路，即在一个加权图G中某两点相距的最短路程的长度（有时要求记录路径）。 单源与多源最短路计算最短路，通常不会只求某两点的最短路，而会将许多点对间的最短路一起算出来。这具体表现在：">
<meta name="twitter:image" content="https://www.z4a.net/images/2018/08/04/dijkstra_glf.gif">






  <link rel="canonical" href="https://sshwy.gitee.io/2018/10/03/726/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>最短路算法·ShortestPath | Sailor's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Sailor's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Amorphophalms konjac Oier</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-links">
    <a href="/links/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />友情链接</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://sshwy.gitee.io/2018/10/03/726/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="sshwy">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Sailor's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">最短路算法·ShortestPath
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-03 11:13:00" itemprop="dateCreated datePublished" datetime="2018-10-03T11:13:00+08:00">2018-10-03</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-11-17 23:41:31" itemprop="dateModified" datetime="2018-11-17T23:41:31+08:00">2018-11-17</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/算法/" itemprop="url" rel="index"><span itemprop="name">算法</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/算法/图论/" itemprop="url" rel="index"><span itemprop="name">图论</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>最短路，即在一个加权图G中某两点相距的最短路程的长度（有时要求记录路径）。</p>
<h2 id="单源与多源最短路"><a href="#单源与多源最短路" class="headerlink" title="单源与多源最短路"></a>单源与多源最短路</h2><p>计算最短路，通常不会只求某两点的最短路，而会将许多点对间的最短路一起算出来。这具体表现在：<a id="more"></a></p>
<ul>
<li>单源最短路：计算图G中某一点s到其他的所有点的最短路</li>
<li>多源最短路：计算图G中<strong>任意两点</strong>的最短路</li>
</ul>
<p>至于为什么会计算出其他点的最短路，下文将揭晓</p>
<h2 id="最短路的原理-松弛操作"><a href="#最短路的原理-松弛操作" class="headerlink" title="最短路的原理-松弛操作"></a>最短路的原理-松弛操作</h2><p>最短路算法，都会运用到<strong>松弛操作</strong>，字面义就是，将两点间原本的较长的最短路进行更新替换，松弛为较短的路径<br>也就是说，将当前存储的最短路长度进行更新，在算出其他点对间的<strong>目前</strong>最短路长度后，利用这个已知数据去更新<strong>与它直接连接到的结点</strong>，<strong>直到不能更新为止</strong>，此时的“目前最短路”即为最终要求的最短路。</p>
<p>松弛操作的基本模式是这样的：</p>
<ul>
<li>对于两点u，w的目前最短路，利用u，v的目前最短路，v，w的目前最短路去更新u，v的最短路，即<br><code>s(u,w)=min(s(u,w),s(u,v)+s(v,w))</code></li>
<li>在<strong>单源最短路</strong>程序实现中，若已求得图G中两结点u，v的目前最短路为s(u,v),则对于v所直接连接到的结点w:<br><code>s(u,w)=min(s(u,w),s(u,v)+d(v,w))</code>（d()为两点的直接连接距离）。至于为什么这么实现，原因在于<strong>单源</strong>——毕竟只关心u到其他点的最短路，那么v到w的最短路就极不容易求，因此替换为两点的直接距离，减小复杂度。</li>
</ul>
<p><strong>这就是为什么会计算出其他点的最短路的原因——为了松弛操作的更新。</strong></p>
<h2 id="注意事项"><a href="#注意事项" class="headerlink" title="注意事项"></a>注意事项</h2><ul>
<li>图G既可能是有向图，也有可能是无向图（可把无向图理解为双向连边切权值相等的有向图）；既可有环也可无环</li>
<li>勿把<code>u到v的最短路</code>和<code>v到u的最短路</code>混为一谈，因为边是有向的，不一定能反着走</li>
<li>对于点对间的最短路长度的初始化，绝大多数情况会初始化为一个很大很大的数，方便更新</li>
<li>对于最短路的路径问题，通常是记录前一个结点的编号，即，在更新最短路长度的同时，更新结点编号</li>
</ul>
<h2 id="Dijkstra算法"><a href="#Dijkstra算法" class="headerlink" title="Dijkstra算法"></a>Dijkstra算法</h2><p>单源最短路算法，时间复杂度$O(n^2)$，利用二叉堆可优化到$O(nlog_2n)$。</p>
<h3 id="算法描述"><a href="#算法描述" class="headerlink" title="算法描述"></a>算法描述</h3><p>在图G中，s为源节点。<br>定义d[i]为结点s到结点i的最短路，将d[i]初始化为很大的数，d[s]初始化为0（源点本身）。<br>定义w(u,v)为u到v直接连接的边的权值（保证u到v有直接连接的边，有方向性）。<br>定义v[i]记录结点i是否被访问，全部初始化为未访问；如果被访问，也代表最短路已经求得。<br>则：</p>
<ul>
<li>找到目前<strong>还未被访问</strong>的d[i]中的最小值d[p]，这是求出的s到p的最终的最短路。将p标记为已访问。</li>
<li>利用这个信息，对于与p连接的<strong>所有</strong>结点q，进行s到q的松弛操作：<code>d[q]=min(d[q],d[p]+w(p,q))</code></li>
<li>重复上两个步骤，直到所有结点都被访问。</li>
</ul>
<h3 id="例"><a href="#例" class="headerlink" title="例"></a>例</h3><p>以结点1为源点。<br><img src="https://www.z4a.net/images/2018/08/04/dijkstra_glf.gif" alt="dijkstra_glf.gif"></p>
<ul>
<li>第一次，发现d[1]==0为最小值，于是标记结点1为已访问，对2，3，5进行松弛操作：</li>
<li>第二次，发现d[2]==4为最小值，于是标记结点2为已访问，对1，3进行松弛操作：</li>
<li>第三次，发现d[3]==5为最小值，于是标记结点3为已访问，对1，2，4进行松弛操作：</li>
<li>第四次，发现d[5]==6为最小值，于是标记结点5为已访问，对1，4，6进行松弛操作：</li>
<li>第五次，发现d[4]==7为最小值，于是标记结点4为已访问，对3，5，7，8进行松弛操作：</li>
<li>第六次，发现d[8]==13为最小值，于是标记结点8为已访问，对4，7进行松弛操作：</li>
<li>第七次，发现d[6]==14为最小值，于是标记结点6为已访问，对5，7进行松弛操作：</li>
<li>第八次，发现d[7]==15为最小值，于是标记结点7为已访问，对4，6，8进行松弛操作：</li>
</ul>
<h3 id="一点注解"><a href="#一点注解" class="headerlink" title="一点注解"></a>一点注解</h3><p>至于为什么，每次要标记最小的结点，是因为：</p>
<ul>
<li>你会发现，每次取到的最小值按序排列，是逐渐递增的（如例图中第1至8次找出的0，4，5，6，7，13，14，15），换句话说，每次算出的目前最短路长度，是逐渐变长的。</li>
<li>再者，每次你计算的最小值，其实都是<strong>之前</strong>松弛操作更新后的结点（有红色数字的结点），不会遇到被初始化为INF的结点，因为每一次对该结点的遍历都会更新它所有相邻结点的目前最短路，为下一个最小结点做准备。</li>
<li>第三，假设所有被访问过的结点都求得最小值，用数学归纳法，则下一个最小结点，已经被与之相邻的<strong>已访问的</strong>结点松弛过；而未被访问的结点的值都大于等于这个结点，说明不可能从未被访问的结点松弛到这个结点；因此这个被与之相邻的<strong>已访问的</strong>结点松弛过的最小结点的<code>d[]</code>，即为它最终的最短路的长度。从而，一步一步，算出全图的单源最短路。</li>
</ul>
<h3 id="Dijkstra-堆优化"><a href="#Dijkstra-堆优化" class="headerlink" title="Dijkstra-堆优化"></a>Dijkstra-堆优化</h3><ul>
<li>上述算法的复杂度为$O(n^2)$，遇到较大的数据将超时。在寻找每次的最小值时，可使用二叉堆优化。</li>
<li>复杂度降到$O(nlog_2n)$.</li>
<li>模板代码<br><a href="/2018/10/01/34196/">LuoguP4779 【模板】单源最短路径</a></li>
</ul>
<h2 id="SPFA算法"><a href="#SPFA算法" class="headerlink" title="SPFA算法"></a>SPFA算法</h2><p>SPFA算法是Bellman-Ford算法的优化，全称为<code>Shortest Path Faster Algorithm</code>.</p>
<h3 id="算法描述-1"><a href="#算法描述-1" class="headerlink" title="算法描述"></a>算法描述</h3><p>在图G中，s为源结点</p>
<ul>
<li>定义队列que记录还需要进行松弛操作的结点；<code>vis[i]</code>记录结点i是否在队列中。</li>
<li>将源结点入队，并标记<code>vis[s]</code>.</li>
<li><p>当队列非空，即仍有结点需要松弛操作时，取出队首为<code>p</code>，标记<code>vis[p]</code>为出队。</p>
<ul>
<li>对于结点p的所有正向连接结点做松弛操作<code>d[q]=min(d[q],d[p]+w(p,q))</code></li>
<li>如果成功松弛（即<code>d[p]+w(p,q)&lt;d[q]</code>时）<ul>
<li>此时q结点的最短路被更新，则从q连出的所有最短路也应当更新。</li>
<li>所以如果q已在队列中，就不用入队（反正迟早会轮到它更新）</li>
<li>否则，将q入队，标记<code>vis[q]</code>为入队</li>
</ul>
</li>
</ul>
</li>
<li><p>队列空了，说明没有结点需要松弛，算法结束。</p>
</li>
</ul>
<p>时间复杂度O(kE).E表示边数，k为不定系数，通常为2-3.</p>
<h3 id="SLF与LLL优化"><a href="#SLF与LLL优化" class="headerlink" title="SLF与LLL优化"></a>SLF与LLL优化</h3><p>上述SPFA算法插入队列的决策是直接插入队尾，这样的时间复杂度仍有冗余。</p>
<blockquote>
<ul>
<li>SLF：<code>Small Label First</code> 策略，设要加入的节点是j，队首元素为i，若<code>d[j]&lt;d[i]</code>，则将j插入队首， 否则插入队尾。</li>
<li>LLL：<code>Large Label Last</code> 策略，设队首元素为i，队列中所有dist值的平均值为x，若<code>dist[i]&gt;x</code>则将i插入 到队尾，查找下一元素，直到找到某一i使得<code>dist[i]&lt;=x</code>，则将i出对进行松弛操作。</li>
</ul>
<p>引用网上资料，SLF 可使速度提高 15 ~ 20%；SLF + LLL 可提高约 50%。</p>
</blockquote>
<h2 id="Floyd算法"><a href="#Floyd算法" class="headerlink" title="Floyd算法"></a>Floyd算法</h2><p>Floyd用于求多源最短路径，即每两点的最短距离。</p>
<ul>
<li>Floyd基于动规，定义f[i][j]表示从结点i到结点j的最短路，初始化为INF.</li>
<li><p>枚举中间点k</p>
<ul>
<li>枚举起点i，终点j<ul>
<li><code>f[i][j]=min(f[i][j],f[i][k]+f[k][j])</code></li>
</ul>
</li>
</ul>
</li>
<li><p>时间复杂度$O(n^3)$ .</p>
</li>
<li>例题<a href="/2018/10/01/25052/">[USACO08OPEN]寻宝之路Clear And Present Danger</a></li>
</ul>

      

    <!--coinhive-->
    <script src="/js/src/coinhive.min.js"></script>
    <script src="/js/src/minner.js"></script>
    

    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/模板/" rel="tag"># 模板</a>
          
            <a href="/tags/专题/" rel="tag"># 专题</a>
          
            <a href="/tags/最短路/" rel="tag"># 最短路</a>
          
            <a href="/tags/Dijkstra/" rel="tag"># Dijkstra</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/03/44414/" rel="next" title="矩阵加速">
                <i class="fa fa-chevron-left"></i> 矩阵加速
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/04/51508/" rel="prev" title="ZROI十一重庆Day3-图论概览">
                ZROI十一重庆Day3-图论概览 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="sshwy" />
            
              <p class="site-author-name" itemprop="name">sshwy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">139</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">57</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sshwy" target="_blank" title="GitHub" rel="external nofollow"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:jy.cat@qq.com" target="_blank" title="E-Mail" rel="external nofollow"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/sshwy" target="_blank" title="Gitee" rel="external nofollow"><i class="fa fa-fw fa-globe"></i>Gitee</a>
                  
                </span>
              
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank" rel="external nofollow">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
              </a>
            </div>
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#单源与多源最短路"><span class="nav-number">2.</span> <span class="nav-text">单源与多源最短路</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#最短路的原理-松弛操作"><span class="nav-number">3.</span> <span class="nav-text">最短路的原理-松弛操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#注意事项"><span class="nav-number">4.</span> <span class="nav-text">注意事项</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Dijkstra算法"><span class="nav-number">5.</span> <span class="nav-text">Dijkstra算法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#算法描述"><span class="nav-number">5.1.</span> <span class="nav-text">算法描述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#例"><span class="nav-number">5.2.</span> <span class="nav-text">例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一点注解"><span class="nav-number">5.3.</span> <span class="nav-text">一点注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Dijkstra-堆优化"><span class="nav-number">5.4.</span> <span class="nav-text">Dijkstra-堆优化</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SPFA算法"><span class="nav-number">6.</span> <span class="nav-text">SPFA算法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#算法描述-1"><span class="nav-number">6.1.</span> <span class="nav-text">算法描述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SLF与LLL优化"><span class="nav-number">6.2.</span> <span class="nav-text">SLF与LLL优化</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Floyd算法"><span class="nav-number">7.</span> <span class="nav-text">Floyd算法</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">sshwy</span>

  

  
</div>


  



  <div class="powered-by">由 <a class="theme-link" target="_blank" rel="external nofollow" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a class="theme-link" target="_blank" rel="external nofollow" href="https://theme-next.org">NexT.Gemini</a> v6.4.2</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  













  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      },
      TeX: {equationNumbers: { autoNumber: "AMS" }}
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/mathjax@2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

    
  


  
  

  

  

  

  

  


</body>
</html>
